<?php
namespace app\index\widget;

use think\Controller;
use app\admin\model\NewsModel;
use app\admin\model\ClassModel;
use app\admin\model\LabelModel;
use app\admin\model\CommentModel;
use app\admin\model\MemberModel;

/**
 * 工具控件
 * @author Alinejun666
 * Date 2018-8-21
 */

class Common extends controller
{

    public function header()
    {
        $user = session('member');
        if (!empty($user)) {
            $diff = (int)time()-(int)strtotime($user['active_time']);
            
            if ($diff > 1800) {
                session('member', null);
                $user = null;
            }else{
                session('member.active_time', date("Y-m-d H:i:s",time()));
            }
        }

        $cname = request()->controller();
        $aname = request()->action();

        $data = [
            'cname'  => strtolower($cname),
            'aname'  => strtolower($aname),
            'member' => $user,
        ];
		return $this->fetch('widget/header', $data);
    }
	
    public function category()
    {
        $class = new ClassModel();

        $where = ['status' => 1];
        $order = "class_id asc";
        $field = "*";

        $list = $class->get_list($where, $order, $field);

		return $this->fetch('widget/category', ['data' => $list]);
    }

    public function news()
    {
        $news = new NewsModel();

        $where = ['status' => 1];
        $order = "create_time desc";
        $start = 0;
        $size  = 8;
        $list  = $news->get_list_page($where, $order, $fields = "*", $start, $size);

		return $this->fetch('widget/news', ['newslist' => $list]);
    }


    public function labels()
    {
        $label = new LabelModel();

        $where = ['status' => 1];
        $order = "label_id asc";
        $list  = $label->get_list($where, $order, $fields = "*");

		return $this->fetch('widget/labels', ['labels' => $list]);
    }

    public function comment()
    {
        $comment = new CommentModel();
        $member  = new MemberModel();

        $where = ['status' => 1];
        $order = "like_count desc";
        $start = 0;
        $size  = 6;        
        $list  = $comment->get_list_page($where, $order, $fields = "*", $start, $size);
        foreach ($list as $k => $v) {
            // 昵称
            $list[$k]['nickname'] = $member->get_field(['user_id' => $v['user_id']], "nickname");
            // 字符截取
            if (mb_strlen($v['content'], "utf-8") > 50) {
                $list[$k]['content'] = mb_substr($v['content'], 0, 50, "utf-8")."..";
            }
        }

        return $this->fetch('widget/comment', ['comment' => $list]);
    }

    public function footer()
    {
		return $this->fetch('widget/footer');
    }

    public function usermenu()
    {
        return $this->fetch('widget/usermenu');
    }

}
